package com.coocaa.typhoon.api.v1.userfile.util;

import com.coocaa.cirrus.common.base.exception.BusinessException;
import com.coocaa.typhoon.api.v1.userfile.constant.FileSceneConstant;
import lombok.experimental.UtilityClass;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.net.URI;
import java.net.URISyntaxException;

/**
 * @author bijiahao
 * @date : 2025/9/19 20:04
 * @description
 */
@Slf4j
@UtilityClass
public class TosFinalUrlUtil {

    /**
     * tos://{tosBucketName}/{filePath}
     *
     * @param tosBucketName
     * @param filePath
     * @return
     */
    public static String getTosLink(String tosBucketName, String filePath) {
        StringBuffer sb = new StringBuffer();
        sb.append("tos://")
                .append(tosBucketName)
                .append("/")
                .append(filePath);
        return sb.toString();
    }

    /**
     * tos://{tosBucketName}/{envDir}/{ FileNameUtil.mainName(parentFileName)}_{parentFileExtName}_{fileScene}_{index}.{fileExtName}
     * 转化 tos://{tosBucketName}/{envDir}/{ FileNameUtil.mainName(parentFileName)}.{parentFileExtName}
     *
     * @param
     * @return
     */
    public static String getParentTosLink(String tosLink) {
        String[] split = tosLink.split("_" + FileSceneConstant.PREVIEW + "_");
        String basePart = split[0];
        String extName = basePart.substring(basePart.lastIndexOf('_') + 1);
        String prefix = basePart.substring(0, basePart.lastIndexOf('_'));
        StringBuffer sb = new StringBuffer();
        sb.append(prefix)
                .append(".")
                .append(extName.toLowerCase());
        return sb.toString();
    }

    public static int extractNumber(String name) {
        int lastUnderscore = name.lastIndexOf('_');
        int dotIndex = name.lastIndexOf(".");
        if (lastUnderscore == -1 || dotIndex == -1) {
            return -1;
        }
        String numStr = name.substring(lastUnderscore + 1, dotIndex);
        try {
            return Integer.parseInt(numStr);
        } catch (NumberFormatException e) {
            return -1;
        }
    }

    public static String getFilePath(String tosLink) {
        try {
            URI uri = new URI(tosLink);
            if (!"tos".equals(uri.getScheme())) {
                throw new IllegalArgumentException("Invalid TOS URL scheme");
            }
            String path = uri.getPath();
            // 移除开头的斜杠（路径格式为"/dir/file.txt"）
            return path.startsWith("/") ? path.substring(1) : path;
        } catch (URISyntaxException e) {
            log.error("getFilePath", e);
            throw new BusinessException("获取文件路径异常");
        }
    }

    /**
     * @param tosUrlPrefix/{filePath}efix
     * @param filePath
     * @return
     */
    public static String getHttpUrl(String tosUrlPrefix, String filePath) {
        StringBuffer sb = new StringBuffer();
        sb.append(tosUrlPrefix)
                .append("/")
                .append(filePath);
        return sb.toString();
    }

    public static void main(String[] args) {
        String tosUrl = "tos://aios-guan/test/5618318815881752.jpg";
        String res = getFilePath(tosUrl);
        System.out.println(res);
        String parentFilePath = "test/56183188_15881752_1.jpg";
        System.out.println(StringUtils.substringBeforeLast(parentFilePath, "_"));

        System.out.println(getParentTosLink("tos://aios-guan/test/20250920_1969350513266921472_PDF_preview_38.png"));
    }
}
